package com.jstyle.jclife.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;

import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.fitness.Fitness;
import com.google.android.gms.fitness.FitnessOptions;
import com.google.android.gms.fitness.data.DataPoint;
import com.google.android.gms.fitness.data.DataSet;
import com.google.android.gms.fitness.data.DataSource;
import com.google.android.gms.fitness.data.DataType;
import com.google.android.gms.fitness.data.Field;
import com.google.android.gms.tasks.OnCanceledListener;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.jstyle.jclife.R;
import com.jstyle.jclife.daoManager.StepDataDaoManager;
import com.jstyle.jclife.daoManager.StepDetailDataDaoManager;
import com.jstyle.jclife.model.StepData;
import com.jstyle.jclife.model.StepDetailData;
import com.jstyle.jclife.utils.DateUtil;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.ButterKnife;
import butterknife.OnClick;

public class ThirdDataActivity extends BaseActivity {

    private GoogleSignInAccount account;
    private int GOOGLE_SIGN_IN=122;
    private static final String TAG = "ThirdDataActivity";
    private FitnessOptions fitnessOptions;
    private int GOOGLE_FIT_PERMISSIONS_REQUEST_CODE=123;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third_data);
        ButterKnife.bind(this);
        init();
    }

    private void init() {
        fitnessOptions = FitnessOptions.builder()
                //步数
                .addDataType(DataType.TYPE_STEP_COUNT_DELTA, FitnessOptions.ACCESS_WRITE)
                //距离
                .addDataType(DataType.TYPE_DISTANCE_DELTA, FitnessOptions.ACCESS_WRITE)
                .addDataType(DataType.TYPE_CALORIES_EXPENDED,FitnessOptions.ACCESS_WRITE)
                .build();
    }

    @OnClick({R.id.button_googleFit, R.id.button_strava})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.button_googleFit:
                connectGoogle();
                break;
            case R.id.button_strava:
                startUpload();
                break;
        }
    }
    public void connectGoogle() {
        try {
            //如果已经登录过google账号。则可以拿到账号
            account= GoogleSignIn.getLastSignedInAccount(this);
            if (account==null) {
                //没有。则要登录
                signIn();
            }else{
                //有，则要订阅
                Subscribe();
            }
        }catch (Exception e){
            e.printStackTrace();

        }
    }
    private void signIn(){
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
        GoogleSignInClient mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
    }
    private void Subscribe(){
        account=GoogleSignIn.getLastSignedInAccount(this);
        if (account==null){
            return;
        }
        //判断是否有写入数据的权限，这个会弹出授权写入数据的弹框
        if (!GoogleSignIn.hasPermissions(account, fitnessOptions)) {
            GoogleSignIn.requestPermissions(
                    this, // your activity
                    GOOGLE_FIT_PERMISSIONS_REQUEST_CODE,
                    account,
                    fitnessOptions);
        }else{
            subscriptionData();
        }
    }

    private void subscriptionData() {
        subscribe(DataType.TYPE_STEP_COUNT_DELTA);// 订阅步数
        subscribe(DataType.TYPE_DISTANCE_DELTA);//
    }
    private void subscribe(final DataType dataType) {
        GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
        if (account == null) {
            return;
        }
        Fitness.getRecordingClient(this, GoogleSignIn.getLastSignedInAccount(this))
                .subscribe(dataType)
                .addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        //每订阅成功一个，会回调这个方法

                        Log.i(TAG, "onSuccess: ");
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.i(TAG, "onFailure: "+e.getMessage());
                    }
                });
    }
    DataSet stepDataSet;
    DataSet distanceDataSet;


    private void startUpload(){
        List<StepDetailData>stepDetailDataList= StepDetailDataDaoManager.queryAllDataAddress();

      //  stepDataSet = createDataForRequest(DataType.TYPE_STEP_COUNT_DELTA,Field.FIELD_STEPS, stepAllCount, lastUploadTime, currentUploadTime);// 步数
       // distanceDataSet = createDataForRequest(DataType.TYPE_DISTANCE_DELTA,Field.FIELD_DISTANCE ,allDistance, lastUploadTime, currentUploadTime);// 距离
     createDataForRequest();
    }
    private void insetData(DataSet dataSet){

        Fitness.getHistoryClient(this, GoogleSignIn.getLastSignedInAccount(this)).insertData(dataSet).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                Log.i(TAG, "onComplete: ");
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.i(TAG, "onFailure: ");
            }
        }).addOnCanceledListener(new OnCanceledListener() {
            @Override
            public void onCanceled() {
                Log.i(TAG, "onCanceled: ");
            }
        });
    }
    private void createDataForRequest() {

        DataSource dataSourceStep =
                new DataSource.Builder()
                        .setAppPackageName(this)
                        .setDataType(DataType.TYPE_STEP_COUNT_DELTA)
                        .setStreamName("streamName")
                        .setType(DataSource.TYPE_RAW)
                        .build();
        DataSet dataSetStep = DataSet.create(dataSourceStep);
        DataSource dataSourceDistance =
                new DataSource.Builder()
                        .setAppPackageName(this)
                        .setDataType(DataType.TYPE_DISTANCE_DELTA)
                        .setStreamName("streamName")
                        .setType(DataSource.TYPE_RAW)
                        .build();
        DataSet dataSetDistance = DataSet.create(dataSourceDistance);

        DataSource dataSourceCal =
                new DataSource.Builder()
                        .setAppPackageName(this)
                        .setDataType(DataType.TYPE_CALORIES_EXPENDED)
                        .setStreamName("streamName")
                        .setType(DataSource.TYPE_RAW)
                        .build();
        DataSet dataSetCal = DataSet.create(dataSourceCal);
//        List<StepData>stepDataList= StepDataDaoManager.queryAllData();
        List<StepDetailData>stepDetailDataList= StepDetailDataDaoManager.queryAllDataAddress();
        for(StepDetailData stepDetailData:stepDetailDataList){
            int step=Integer.valueOf(stepDetailData.getStep());
            float distance=Float.valueOf(stepDetailData.getDistance());
            float cal=Float.valueOf(stepDetailData.getCal());
            String time=stepDetailData.getDate();
           // Log.i(TAG, "createStepDataForRequest: "+time+" "+step+" "+distance);
            long startTime= DateUtil.getDefaultLongMi(time);
            long endTime=startTime+9*60*1000l;
            if(endTime>System.currentTimeMillis())endTime=System.currentTimeMillis();
            DataPoint dataPoint =
                    dataSetStep.createDataPoint().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
            dataPoint.setIntValues(step>2000?2000:step);
            dataSetStep.add(dataPoint);
            DataPoint dataPointDis =
                    dataSetDistance.createDataPoint().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
            dataPointDis.setFloatValues(distance*1000);
            dataSetDistance.add(dataPointDis);

            DataPoint dataPointCal =
                    dataSetCal.createDataPoint().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
            dataPointCal.setFloatValues(cal);
            dataSetCal.add(dataPointCal);
        }
       insetData(dataSetStep);
       insetData(dataSetDistance);
       insetData(dataSetCal);
    }
    /**
     * //创建要上传的数据对象
     * @param dataType DataType类型
     * @param field Field类型
     * @param values 数据值
     * @param startTime 开始时间戳
     * @param endTime 结束时间戳
     * @return
     * 开始时间戳必须小于结束时间戳，不然就抛异常
     */
    private DataSet createDataForRequest(DataType dataType, Field field, Object values, long startTime, long endTime) {
        DataSource dataSource =
                new DataSource.Builder()
                        .setAppPackageName(this)
                        .setDataType(dataType)
                        .setStreamName("streamName")
                        .setType(DataSource.TYPE_RAW)
                        .build();
        DataSet dataSet = DataSet.create(dataSource);
        DataPoint dataPoint =
                dataSet.createDataPoint().setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS);
        if (dataType == DataType.TYPE_CALORIES_EXPENDED||dataType==DataType.TYPE_HEART_RATE_BPM) {
            dataPoint.getValue(field).setFloat((Float) values);
        } else {
            //如果是float类型则要调用setFloagValues
            if (values instanceof Integer) {
                dataPoint.setIntValues((Integer) values);
            } else {
                dataPoint = dataPoint.setFloatValues((Float) values);
            }
        }
        dataSet.add(dataPoint);
        return dataSet;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult: "+requestCode+" "+resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == GOOGLE_FIT_PERMISSIONS_REQUEST_CODE) {
                subscriptionData();
            }else if(requestCode == GOOGLE_SIGN_IN){
                Subscribe();
            }
        }
    }
}
